package com.quan.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseServiceImpl;
import com.quan.commons.core.utils.PageUtils;
import com.quan.mall.commons.vo.FmsMemberCommisionFreezeVo;
import com.quan.mall.entity.FmsMemberCashFlow;
import com.quan.mall.entity.FmsMemberCommisionFreeze;
import com.quan.mall.entity.FmsMemberWallet;
import com.quan.mall.mapper.FmsMemberCommisionFreezeMapper;
import com.quan.mall.service.FmsMemberCashFlowService;
import com.quan.mall.service.FmsMemberCommisionFreezeService;
import com.quan.mall.service.FmsMemberWalletService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class FmsMemberCommisionFreezeServiceImpl extends MyBaseServiceImpl<FmsMemberCommisionFreezeMapper, FmsMemberCommisionFreeze> implements FmsMemberCommisionFreezeService {

    @Autowired
    private FmsMemberCommisionFreezeMapper mapper;

    @Autowired
    private FmsMemberWalletService fmsMemberWalletService;

    @Autowired
    private FmsMemberCashFlowService fmsMemberCashFlowService;

    @Override
    public List<FmsMemberCommisionFreezeVo> queryList(PageUtils pageUtils, FmsMemberCommisionFreezeVo vo) {
        QueryWrapper<FmsMemberCommisionFreeze> queryWrapper = new QueryWrapper<FmsMemberCommisionFreeze>(vo);

        List<FmsMemberCommisionFreeze> list = super.list(pageUtils, queryWrapper);
        List<FmsMemberCommisionFreezeVo> collect = list.stream().map(item -> {
            FmsMemberCommisionFreezeVo bean = new FmsMemberCommisionFreezeVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, FmsMemberCommisionFreezeVo vo) {
        QueryWrapper<FmsMemberCommisionFreeze> queryWrapper = new QueryWrapper<FmsMemberCommisionFreeze>(vo);

        if (StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("name", vo.getKeyword());
            });
        }

        // 时间选择->0:今天;1:昨天;2:最近7天;3:最近30天:4:本月;5本年
        if (null != vo.getDateAttr()) {
            if (vo.getDateAttr() == 0) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0}", LocalDate.now());
            } else if (vo.getDateAttr() == 1) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0}", LocalDate.now().plusDays(-1));
            } else if (vo.getDateAttr() == 2) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-7), LocalDate.now());
            } else if (vo.getDateAttr() == 3) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-30), LocalDate.now());
            } else if (vo.getDateAttr() == 4) {
                // 本月的第一天
                final LocalDate firstMonthDay = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
                // 本月的最后一天
                final LocalDate lastMonthDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfMonth());
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", firstMonthDay, lastMonthDay);
            } else if (vo.getDateAttr() == 5) {
                // 今年的第一天
                final LocalDate firstYearDay = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
                // 今年的最后一天
                final LocalDate lastYearDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfYear());
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", firstYearDay, lastYearDay);
            }
        } else {
            // 下单日期范围
            if (StringUtils.isNotEmpty(vo.getDateRange())) {
                final String[] split = vo.getDateRange().split(",");
                String startDate = split[0];
                String endDate = split[1];
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", startDate, endDate);
            }
        }

        final IPage<FmsMemberCommisionFreeze> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<FmsMemberCommisionFreeze> records = page.getRecords();

        final List<FmsMemberCommisionFreeze> collect = records.stream().map((item) -> {
            FmsMemberCommisionFreezeVo bean = new FmsMemberCommisionFreezeVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Transactional
    @Override
    public R enterNow(Long id) {
        // 当前冻结金额状态为：2入账
        final FmsMemberCommisionFreeze freeze = super.getById(id);
        freeze.setStatus(2);
        updateById(freeze);

        // 将记录转移到会员交易流水表中
        FmsMemberCashFlow cashFlow = new FmsMemberCashFlow();
        BeanUtils.copyProperties(freeze, cashFlow);

        cashFlow.setSaleGoodsOrderSn(freeze.getSaleGoodsOrderSn());
        cashFlow.setSaleGoodsOrderAmount(freeze.getSaleGoodsOrderAmount());

        cashFlow.setTransactionAmount(freeze.getFreezeAmount());
        cashFlow.setTransactionType(freeze.getBankrollType());
        this.fmsMemberCashFlowService.save(cashFlow);


        // 将入账金额存入会员钱包中
        final FmsMemberWallet wallet = this.fmsMemberWalletService.getMemberWallter(freeze.getMemberId());
        wallet.setAmount(wallet.getAmount().add(freeze.getFreezeAmount()));
        this.fmsMemberWalletService.updateById(wallet);


        return R.ok();
    }

    @Override
    public List<FmsMemberCommisionFreeze> getMemberFreezeList(Long memberId) {
        QueryWrapper<FmsMemberCommisionFreeze> queryWrapper = new QueryWrapper<FmsMemberCommisionFreeze>();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", 1);

        return super.list(queryWrapper);
    }

    @Override
    public List<FmsMemberCommisionFreeze> getFreezeByOrderSn(String orderSn) {
        QueryWrapper<FmsMemberCommisionFreeze> queryWrapper = new QueryWrapper<FmsMemberCommisionFreeze>();
        queryWrapper.eq("sale_goods_order_sn", orderSn);
        queryWrapper.eq("status", 3);
        queryWrapper.eq("bankroll_type", 2);
        queryWrapper.eq("bankroll_type", 2);

        return super.list(queryWrapper);
    }
}